<template>
    <div class="container_box">
        <el-scrollbar class="main_box2">
            <div class="contract_amount_container">
                <el-form
                    ref="ruleFormRef"
                    :disabled="disabled"
                    :model="ruleForm"
                    :rules="rules"
                    label-width="140px"
                    class="demo-ruleForm">
                    <el-card shadow="never" class="mb-16 bdt_none">
                        <div class="tittle">基本信息</div>
                        <el-divider />
                        <div class="content">
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="合同标题" prop="title">
                                        <el-input
                                            v-model="ruleForm.title"
                                            maxlength="20"
                                            clearable
                                            show-word-limit
                                            placeholder="请输入合同标题" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item class="belong_staff" label="所属员工" prop="belong_staff_id">
                                        <ZWSelectDepart v-model="ruleForm.belong_staff_id" :creators="creators" />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="客户类型" prop="cust_type">
                                        <el-select
                                            v-model="ruleForm.cust_type"
                                            disabled
                                            placeholder="请选择客户类型"
                                            class="w-100">
                                            <el-option label="个人客户" value="1" />
                                            <el-option label="企业客户" value="2" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="合同客户" prop="cust_id">
                                        <el-button @click="openCustomer">选择客户</el-button>
                                        <!--选择客户 -->
                                        <el-tag
                                            v-for="(item, index) in cust_arr"
                                            :key="item.crop_name ?? item.name"
                                            type="warning"
                                            closable
                                            class="staffs_item"
                                            @close="handleClose(item, index)">
                                            {{ item?.crop_name || item?.name }}
                                        </el-tag>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row v-if="isAccount">
                                <el-col :span="12">
                                    <el-form-item label="社会统一信用代码" prop="uscc">
                                        <el-input
                                            v-model="ruleForm.uscc"
                                            clearable
                                            placeholder="请输入社会统一信用代码"
                                            maxlength="18" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="法人姓名" prop="legal_person">
                                        <el-input
                                            v-model="ruleForm.legal_person"
                                            clearable
                                            placeholder="请输入法人姓名"
                                            @input="inputMapLabel($event, 'legal_person')" />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row v-if="isAccount">
                                <el-col :span="12">
                                    <el-form-item label="业务联系人" prop="business_contact">
                                        <el-input
                                            v-model="ruleForm.business_contact"
                                            clearable
                                            placeholder="请输入业务联系人"
                                            @input="inputMapLabel($event, 'business_contact')" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="业务联系人身份证" prop="business_id_card">
                                        <el-input
                                            v-model="ruleForm.business_id_card"
                                            clearable
                                            placeholder="请输入业务联系人身份证"
                                            maxlength="18" />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row>
                                <el-col v-if="isAccount" :span="12">
                                    <el-form-item label="业务联系人手机" prop="business_contact_mobile">
                                        <el-input
                                            v-model="ruleForm.business_contact_mobile"
                                            clearable
                                            placeholder="请输入业务联系人手机"
                                            maxlength="11"
                                            @input="inputMapLabel($event, 'business_contact_mobile')" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="合同金额" prop="contract_amount">
                                        <div class="contract_amount_wrap">
                                            <el-input-number
                                                v-model="ruleForm.contract_amount"
                                                :min="0"
                                                class="w-50 mr-8"
                                                placeholder="0.00"
                                                @blur="handleBlur(ruleForm.contract_amount)"
                                                @input="inputMapLabel($event, 'contract_amount')"></el-input-number>
                                            <span>元</span>
                                        </div>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row>
                                <el-col v-if="isAccount" :span="12">
                                    <el-form-item label="营业执照" prop="business_license">
                                        <ZWUpload
                                            ref="ZWUploadRef"
                                            :disab="isAccount"
                                            @submit="getFile"
                                            @remove="removeFile"></ZWUpload>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="合同有效期" prop="contract_life">
                                        <div class="contract_amount_wrap">
                                            <el-input
                                                v-model="ruleForm.contract_life"
                                                class="w-50 mr-8"
                                                clearable
                                                placeholder="请输入合同有效期"
                                                @blur="handleBlurLife(ruleForm.contract_life)">
                                            </el-input>
                                            <el-select v-model="ruleForm.contract_life_type">
                                                <el-option label="年" value="2"></el-option>
                                                <el-option label="月" value="1"></el-option>
                                            </el-select>
                                        </div>
                                    </el-form-item>
                                    <el-form-item label="合同模版" prop="contract_template_id">
                                        <el-select
                                            v-model="ruleForm.contract_template_id"
                                            placeholder="请选择合同模版"
                                            class="w-100"
                                            @change="handleChangeTpl">
                                            <el-option
                                                v-for="item in templtetList"
                                                :key="item.id"
                                                :label="item.template_name"
                                                :value="item.id" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </el-card>

                    <el-card shadow="never" class="bdb_none">
                        <div class="tittle">模版参数</div>
                        <el-divider />
                        <div class="content diy_form_content">
                            <div v-for="(item, index) in ruleForm.contract_template_params" :key="item.id" class="w-50">
                                <el-form-item
                                    v-if="item.type == 'email'"
                                    :label="item.name"
                                    :rules="[
                                        {
                                            required: item.is_required == 2 ? true : false,
                                            validator: item.is_required == 2 ? checEmail1 : checEmail,
                                            trigger: 'blur'
                                        }
                                    ]"
                                    :prop="`contract_template_params[${index}].${item.prop}`">
                                    <el-input
                                        v-model="ruleForm.contract_template_params[index].current_val"
                                        :disabled="item.is_edit == 1"
                                        clearable
                                        :placeholder="item.placeholder" />
                                </el-form-item>

                                <el-form-item
                                    v-else-if="item.type == 'mobile'"
                                    :label="item.name"
                                    :rules="[
                                        {
                                            required: item.is_required == 2 ? true : false,
                                            validator: item.is_required == 2 ? checDynamicMobile1 : checDynamicMobile,
                                            trigger: 'blur'
                                        }
                                    ]"
                                    :prop="`contract_template_params[${index}].${item.prop}`">
                                    <el-input
                                        v-model="ruleForm.contract_template_params[index].current_val"
                                        :disabled="item.is_edit == 1"
                                        clearable
                                        maxlength="11"
                                        :placeholder="item.placeholder" />
                                </el-form-item>

                                <el-form-item
                                    v-else
                                    :label="item.name"
                                    :rules="[
                                        {
                                            required: item.is_required == 2 ? true : false,
                                            message: item.placeholder,
                                            trigger:
                                                item.type == 'muti_select' ||
                                                item.type == 'select' ||
                                                item.type == 'date'
                                                    ? 'blur'
                                                    : 'blur'
                                        }
                                    ]"
                                    :prop="`contract_template_params[${index}].${item.prop}`">
                                    <el-select
                                        v-if="item.type == 'muti_select'"
                                        v-model="ruleForm.contract_template_params[index].current_val"
                                        class="w-100"
                                        :disabled="item.is_edit == 1"
                                        :placeholder="item.placeholder"
                                        multiple>
                                        <el-option
                                            v-for="itm in item.options"
                                            :key="itm.value"
                                            :label="itm.name"
                                            :value="itm.value">
                                        </el-option>
                                    </el-select>

                                    <div
                                        v-if="item.type == 'textbox' && item.attr_type == 'string'"
                                        class="diy_form_item_content_input">
                                        <el-input
                                            v-if="item.type == 'textbox'"
                                            v-model="ruleForm.contract_template_params[index].current_val"
                                            clearable
                                            min="0"
                                            :disabled="item.is_edit == 1"
                                            :placeholder="item.placeholder" />
                                        <span v-if="item.suffix">{{ item.suffix }}</span>
                                    </div>

                                    <div
                                        v-if="item.type == 'textbox' && item.attr_type == 'number'"
                                        class="diy_form_item_content_input">
                                        <el-input
                                            v-if="item.type == 'textbox'"
                                            v-model="ruleForm.contract_template_params[index].current_val"
                                            clearable
                                            :type="item.attr_type == 'number'"
                                            min="0"
                                            :disabled="item.is_edit == 1"
                                            :placeholder="item.placeholder"
                                            @blur="
                                                handleChangeBlur(
                                                    ruleForm.contract_template_params[index].current_val,
                                                    item,
                                                    index
                                                )
                                            " />
                                        <span v-if="item.suffix">{{ item.suffix }}</span>
                                    </div>

                                    <el-select
                                        v-if="item.type == 'select'"
                                        v-model="ruleForm.contract_template_params[index].current_val"
                                        class="w-100"
                                        :disabled="item.is_edit == 1"
                                        :placeholder="item.placeholder">
                                        <el-option
                                            v-for="itm in item.options"
                                            :key="itm.value"
                                            :label="itm.name"
                                            :value="itm.value">
                                        </el-option>
                                    </el-select>

                                    <el-date-picker
                                        v-if="item.type == 'date'"
                                        v-model="ruleForm.contract_template_params[index].current_val"
                                        value-format="YYYY-MM-DD"
                                        style="width: 100%"
                                        class="w-100"
                                        :disabled="item.is_edit == 1"
                                        type="date"
                                        :placeholder="item.placeholder" />
                                </el-form-item>
                            </div>
                        </div>
                    </el-card>
                </el-form>
            </div>

            <ZWCustomer
                v-if="visible"
                ref="ZWCustomerRef"
                :selected-ids="selectedIds"
                :sync_type="2"
                @submit="getCust" />
            <ZWDeletdialog ref="submitRef" @submit="submitHandel" />
        </el-scrollbar>
        <div v-if="!disabled" class="footer_box">
            <el-button @click="router.push('/salesleads/salesmanagement/contractmanagement')">取消</el-button>
            <el-button type="primary" @click="save(ruleFormRef, 2)">保存并提交</el-button>
            <el-button type="primary" @click="save(ruleFormRef, 1)">保存</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import ZWSelectDepart from '@/components/ZWSelectDepart.vue';
import ZWCustomer from '@/components/ZWCustomer.vue';
import ZWUpload from './ZWUpload.vue';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import { ref, reactive, computed, onActivated, onMounted, onUnmounted, nextTick } from 'vue';
import {
    getTtemplate,
    createContract,
    getWork,
    getContractDetail,
    getAccount,
    contractedit
} from '@/api/salesleads/contractmanagement/contract';
import { getCustomerDetail } from '@/api/customerCenter';
import type { FormInstance, FormRules } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';

import lodash from 'lodash';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();
const pageType = ref(route.query.pageType || '');

const ZWCustomerRef = ref<any>(null);
const ZWUploadRef = ref<any>(null);
const ruleFormRef = ref<FormInstance>();

const disabled = ref(false);

const cust_arr = ref([]);

const imageUrl = ref('');

const templtetList = ref([]);

const creators = ref([]);

const isAccount = ref(false);

const visible = ref(false);

const map_parameters = ref<Array<any>>([]);
const selectedIds = ref<Array<any>>([]);

const ruleForm = ref({
    title: '', //合同标题
    belong_staff_id: '', //所属员工id
    cust_type: '2', //客户类型1-个人 2-企业
    cust_id: '', //合同客户id
    uscc: '', //统一社会信用代码
    legal_person: '', //法人姓名
    business_contact: '', //业务联系人
    business_id_card: '', //业务联系人身份证
    business_contact_mobile: '', //业务联系人手机
    business_license: '', //营业执照
    contract_amount: '', //合同金额
    contract_life_type: '2', //合同有效期 1-月 2-年
    contract_life: '', //合同有效期
    contract_template_id: '', //合同模版id
    contract_template_params: [] //合同模版属性
});

const submitRef = ref(null);

const submitHandel = () => {
    const data = lodash.cloneDeep(ruleForm.value);
    if (Array.isArray(data.belong_staff_id)) {
        ruleForm.value.belong_staff_id = data.belong_staff_id[0];
    }
    if (pageType.value == 'edit') {
        contractedit({ ...ruleForm.value, type: 2 }).then((res: any) => {
            if (res) {
                ElMessage.success('保存成功');
                setTimeout(() => {
                    router.push('/salesleads/salesmanagement/contractmanagement');
                }, 500);
            }
        });
    } else {
        createContract({ ...ruleForm.value, type: 2 }).then((res: any) => {
            if (res) {
                ElMessage.success('保存成功');
                setTimeout(() => {
                    router.push('/salesleads/salesmanagement/contractmanagement');
                }, 500);
            }
        });
    }
};

const checUscc = (rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('请输入统一社会信用代码'));
    } else if (!/^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))$/.test(value)) {
        callback(new Error('请输入正确格式的统一社会信用代码!'));
    } else {
        callback();
    }
};

const checIdCard = (rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('请输入业务联系人身份证'));
    } else if (
        !/^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/.test(
            value
        )
    ) {
        callback(new Error('请输入正确格式的业务联系人身份证!'));
    } else {
        callback();
    }
};
const checMobile = (rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('请输入业务联系人手机'));
    } else if (!/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确格式的业务联系人手机!'));
    } else {
        callback();
    }
};

const checEmail = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback();
    } else if (
        !/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
            value
        )
    ) {
        callback(new Error('请输入正确格式的邮箱!'));
    } else {
        callback();
    }
};

const checEmail1 = (rule: any, value: any, callback: any) => {
    if (value == '' || !value) {
        callback(new Error('请输入邮箱!'));
    } else if (
        !/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
            value
        )
    ) {
        callback(new Error('请输入正确格式的邮箱!'));
    } else {
        callback();
    }
};

const checDynamicMobile = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback();
    } else if (!/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确格式的手机号!'));
    } else {
        callback();
    }
};
const checDynamicMobile1 = (rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('请输入手机号!'));
    } else if (!/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确格式的手机号!'));
    } else {
        callback();
    }
};

const rules = reactive<FormRules>({
    title: [{ required: true, message: '请输入合同标题', trigger: 'blur' }],
    belong_staff_id: [
        {
            required: true,
            message: '请选择所属员工',
            trigger: 'change'
        }
    ],
    cust_type: [
        {
            required: true,
            message: '请选择客户类型',
            trigger: 'change'
        }
    ],
    cust_id: [
        {
            required: true,
            message: '请选择合同客户',
            trigger: 'change'
        }
    ],
    contract_template_id: [
        {
            required: true,
            message: '请选择合同模版',
            trigger: 'change'
        }
    ],
    uscc: [
        {
            required: true,
            trigger: 'blur',
            validator: checUscc
        }
    ],
    legal_person: [
        {
            required: true,
            message: '请输入法人姓名',
            trigger: 'blur'
        }
    ],
    business_contact: [
        {
            required: true,
            message: '请输入业务联系人',
            trigger: 'blur'
        }
    ],
    business_id_card: [
        {
            required: true,
            trigger: 'blur',
            validator: checIdCard
        }
    ],
    business_license: [
        {
            required: true,
            message: '请上传营业执照',
            trigger: 'change'
        }
    ],
    contract_amount: [
        {
            required: true,
            message: '请输入合同金额',
            trigger: 'blur'
        }
    ],
    business_contact_mobile: [
        {
            required: true,
            trigger: 'blur',
            validator: checMobile
        }
    ],
    contract_life: [
        {
            required: true,
            message: '请输入合同有效期',
            trigger: 'blur'
        }
    ]
});
const save = async (formEl: FormInstance | undefined, type: number) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (type == 2) {
                submitRef.value.appDialog.title = '保存并提交提醒';
                submitRef.value.content = '您确定要保存并提交审批吗？';
                submitRef.value.appDialog.visible = true;
                return;
            }
            const data = lodash.cloneDeep(ruleForm.value);
            if (Array.isArray(data.belong_staff_id)) {
                ruleForm.value.belong_staff_id = data.belong_staff_id[0];
            }
            if (pageType.value == 'edit') {
                contractedit({ ...ruleForm.value, type }).then((res: any) => {
                    if (res) {
                        ElMessage.success('保存成功');
                        setTimeout(() => {
                            router.push('/salesleads/salesmanagement/contractmanagement');
                        }, 500);
                    }
                });
            } else {
                createContract({ ...ruleForm.value, type }).then((res: any) => {
                    if (res) {
                        ElMessage.success('保存成功');
                        setTimeout(() => {
                            router.push('/salesleads/salesmanagement/contractmanagement');
                        }, 500);
                    }
                });
            }
        } else {
        }
    });
};

//打开选择客户弹框
const openCustomer = () => {
    visible.value = true;
    setTimeout(() => {
        ZWCustomerRef.value.appDialog.title = '选择客户';
        ZWCustomerRef.value.appDialog.multiple = false;
        ZWCustomerRef.value.appDialog.visible = true;
    }, 0);
};

// 获取选择客户
const getCust = async (res: any) => {
    visible.value = false;
    if (res) {
        selectedIds.value = [res.id];
        cust_arr.value = [res];
        ruleForm.value.cust_id = res.id;
        ZWCustomerRef.value.departVisble = false;
        ruleFormRef.value.validateField('cust_id');
        const data = await getAccount({ cust_id: res.id });
        mapEnterpriseInfo(data.info);
        isAccount.value = !data.is_account;
        handleChangeContract(1, data);
    }
};
const mapEnterpriseInfo = (info: any) => {
    const list = ['corp_name', 'business_email', 'address'];
    ruleForm.value.contract_template_params.forEach((item: any) => {
        if (list.includes(item.map_field)) {
            item['current_val'] = info[item.map_field] || '';
        }
    });
};

// 移除客户
const handleClose = (item: any, index: number) => {
    visible.value = false;
    cust_arr.value.splice(index, 1);
    ruleForm.value.cust_id = '';
    handleChangeContract(2, null);
    isAccount.value = false;
};

const getFile = (files: any) => {
    if (files.length > 0) {
        ruleForm.value.business_license = files[0].url;
        ruleFormRef.value.validateField('business_license');
    }
};

const removeFile = (files: any) => {
    ruleForm.value.business_license = '';
};

const inputMapLabel = ($event: any, label: string) => {
    const field = map_parameters.value
        .find(item => item.id == ruleForm.value.contract_template_id)
        .fieldList.find((ite: any) => ite.label == label);
    if (field) {
        if ($event < 0 && label == 'contract_amount') {
            return;
        } else {
            ruleForm.value.contract_template_params[field.index].current_val = $event;
        }
    }
};

const getTtemplateFunc = async () => {
    const res = await getTtemplate();
    !!res.length && mapParameters(res);
    templtetList.value = res;
};

const mapParameters = (arr: any[]) => {
    map_parameters.value = arr.map((item: any) => {
        let fieldList = [];
        if (item?.template_params?.length) {
            fieldList = item.template_params.reduce((pre: any, cur: any, index: number) => {
                if (cur.map_field) {
                    pre.push({ label: cur.map_field, index });
                }
                return pre;
            }, []);
        }
        item['fieldList'] = fieldList;
        return item;
    }, []);
};

// 切换合同模版
const handleChangeTpl = (val: any) => {
    const arr = templtetList.value.filter(v => v.id == val);
    if (arr) {
        const tpl_params = lodash.cloneDeep(arr[0].template_params);
        for (let index = 0; index < tpl_params.length; index++) {
            const ele = tpl_params[index];
            ele.current_val = '';
            ele.prop = 'current_val';
            if (ele.type == 'muti_select') {
                ele.current_val = [];
            }
        }
        ruleForm.value.contract_template_params = tpl_params;
    } else {
        ruleForm.value.contract_template_params = [];
    }
};
const getWorkData = () => {
    getWork().then(async (res: any) => {
        if (res.is_work) {
            creators.value = [{ id: res.work_user_id, name: res.work_user_name }];
        }
    });
};

const getDetails = async () => {
    await getTtemplateFunc();
    getContractDetail({ id: route.query.id }).then(async (res: any) => {
        ruleForm.value = res;
        const arr = templtetList.value.filter(v => v.id == res.contract_template_id);
        if (arr) {
            const tpl_params = arr[0].template_params;
            tpl_params.forEach((e: any) => {
                e.prop = 'current_val';
                res.contract_template_params.forEach((m: any) => {
                    m.prop = 'current_val';
                    if (e.system_code == m.system_code) {
                        e.current_val = m.current_val;
                    }
                });
            });
            ruleForm.value.contract_template_params = tpl_params;
        }

        ruleForm.value.cust_type = String(res.cust_type);
        ruleForm.value.contract_life_type = String(res.contract_life_type);
        if (res.cust_info) {
            isAccount.value = true;
        }
        cust_arr.value = [res.cust_info];
        selectedIds.value = [res.cust_info.id];
        if (res.business_license) {
            setTimeout(() => {
                ZWUploadRef.value.uploadFileList = [{ url: res.business_license, name: 'name' }];
            }, 0);
        }

        const data = await getAccount({ cust_id: res.cust_id });
        isAccount.value = !data.is_account;
    });
};

const handleBlurLife = (val: any) => {
    if (val < 0) {
        ruleForm.value.contract_life = Math.abs(Number(val));
    }
};

/**
 * 动态表单和固定表单映射字段
 * 合同金额
 * of start
 */
const handleBlur = (val: any) => {
    if (val < 0) {
        ruleForm.value.contract_amount = Math.abs(Number(val)).toFixed(2);
        return;
    }
    ruleForm.value.contract_amount = Number(val).toFixed(2);
    // ruleForm.value.contract_template_params.forEach((e,i)=>{
    //   for (const key in e) {
    //     if (Object.prototype.hasOwnProperty.call(e, key)) {
    //       if(key == 'map_field'){
    //         ruleForm.value.contract_template_params[i].current_val =  Number(val).toFixed(2)
    //       }
    //     }
    //   }
    // })
};

const handleChangeBlur = (val: any, item: any, index: any) => {
    if (item.system_code == 'tax_rate' && val < 0) {
        ruleForm.value.contract_template_params[index].current_val = Math.abs(Number(val)).toFixed(2);
        return;
    }
    if (!item['map_field']) return;
    ruleForm.value.contract_template_params.forEach((e, i) => {
        for (const key in item) {
            if (Object.prototype.hasOwnProperty.call(e, key)) {
                if (key == 'map_field') {
                    if (e.attr_type == 'number') {
                        ruleForm.value.contract_template_params[index].current_val = Number(val || '0').toFixed(2);
                        ruleForm.value[e[key]] = Number(val || '0').toFixed(2);
                    } else {
                        ruleForm.value[e[key]] = val;
                    }
                }
            }
        }
    });
};

const InitInputMapLabel = (arr?: any[]) => {
    const list = ['legal_person', 'business_contact', 'business_contact_mobile', 'contract_amount'];
    const mapList = [];
    if (arr) {
        mapList.push(...arr);
    } else {
        mapList.push(...list);
    }
    mapList.forEach((item: string) => {
        inputMapLabel(ruleForm.value[item], item);
    });
};

const handleChangeContract = (type: any, data: any) => {
    if (type == 1) {
        ruleForm.value.business_contact = data.info.business_contact;
        ruleForm.value.business_contact_mobile = data.info.business_contact_mobile;
        ruleForm.value.business_id_card = data.info.business_id_card;
        ruleForm.value.business_license = data.info.business_license;
        ruleForm.value.legal_person = data.info.legal_person;
        ruleForm.value.uscc = data.info.uscc;
        InitInputMapLabel(['legal_person', 'business_contact', 'business_contact_mobile']);
        if (data.info.business_license) {
            setTimeout(() => {
                ZWUploadRef.value.uploadFileList = [{ name: 'name', url: data.info.business_license }];
            }, 1000);
        }

        ruleFormRef.value?.clearValidate('contract_template_params[0].current_val');
        // contract_template_params[0].current_val
    } else {
        ruleForm.value.business_contact = '';
        ruleForm.value.business_contact_mobile = '';
        ruleForm.value.business_id_card = '';
        ruleForm.value.business_license = '';
        ruleForm.value.legal_person = '';
        ruleForm.value.uscc = '';
        isAccount.value && (ZWUploadRef.value.uploadFileList = []);
    }
};

/**
 * of end
 */

const setFormValue = async () => {
    await getTtemplateFunc();
    if (templtetList.value) {
        const tpl_params = templtetList.value[0]?.template_params;
        tpl_params.forEach((e: any) => {
            e.prop = 'current_val';
            ruleForm.value.contract_template_params.forEach((m: any) => {
                m.prop = 'current_val';
                if (e.system_code == m.system_code) {
                    e.current_val = m.current_val;
                }
            });
        });
        ruleForm.value.contract_template_params = tpl_params;
    }
    ruleForm.value.contract_template_id = templtetList.value[0]?.id;
    ruleFormRef.value?.clearValidate();
};

onMounted(() => {
    getWorkData();
    getTtemplateFunc();

    if (pageType.value == 'edit' || pageType.value == 'detail') {
        getDetails();
    } else {
        setFormValue();
        setTimeout(() => {
            // ruleFormRef.value?.clearValidate('contract_template_params[1].current_val')
        }, 1);
    }
    if (pageType.value == 'detail') {
        disabled.value = true;
    }
});
</script>
<style lang="scss" scoped>
.contract_amount_container {
    // position:relative;
    // width: 100%;
    // height: 100%;
    // overflow: auto;
}

.mb-16 {
    margin-bottom: 16px;
}

.bdt_none {
    border-top: none;
}

.bdb_none {
    border-bottom: none;
}

.tittle {
    font-size: 16px;
    font-weight: 500;
    color: #33302d;
    line-height: 14px;
}

.content {
    padding: 0 24px 24px;

    .item_title {
        font-size: 14px;
        line-height: 1.125rem;
        font-family: STHeitiSC-Medium, STHeitiSC;
        font-weight: 500;
        color: #33302d;
        margin-bottom: 8px;

        .title_icon {
            display: block;
            height: 1.125rem;
            width: 0.1875rem;
            background: #ff6b00;
            float: left;
            margin-left: -0.9375rem;
        }
    }
}

.save-btn {
    width: 100%;
    height: 54px;
    position: absolute;
    bottom: 0;
    right: 0;
    box-sizing: border-box;
    background: #fbfbfb;
    padding: 0 16px;
    z-index: 9;

    .btn-content {
        width: 100%;
        height: 54px;
        background: #fff;
        box-shadow: 0 0 10px 0 rgb(212 212 212 / 50%);
        border-radius: 2px;
        display: flex;
        align-items: center;
        justify-content: end;
        padding-right: 24px;
        box-sizing: border-box;
    }
}

.w-100 {
    width: 100%;
}

.staffs_item {
    margin-left: 18px;
    background: #fffaf9;
    border-radius: 2px;
    border: 1px solid #ffc69e;
    color: #ff6b00;
}

.el-tag__close {
    color: #ff6b00;

    :deep(.icon) {
        color: #ff6b00;
    }
}

.w-50 {
    width: 50%;
}

.contract_amount_wrap {
    display: flex;

    // justify-content: space-between;
    span {
        width: 50%;
    }

    .mr-8 {
        margin-right: 8px;
    }
}

.diy_form_content {
    display: flex;
    flex-flow: row wrap;
}

.diy_form_item_content_input {
    display: flex;
}

.belong_staff {
    :deep .el-form-item__content {
        display: flex;

        .el-button {
            margin-right: 18px;
        }
    }
}
</style>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
